package com.example.watchcat2k.finalproject;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Call;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Observer;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;




import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class RegisterUserActivity extends AppCompatActivity {
    ImageView imageView;
    EditText account;
    EditText name;
    EditText password;
    EditText confirm_password;
    TextView goto_login;

    Button register;
    Button clear;

    String my_image = null;
    Boolean have_choose = false;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_register);

        init();
        set_click();

    }

    void init(){
        imageView = (ImageView)findViewById(R.id.image);
        account = (EditText)findViewById(R.id.register_username);
        name = (EditText)findViewById(R.id.register_name);
        password = (EditText)findViewById(R.id.register_password);
        confirm_password = (EditText)findViewById(R.id.register_confirm);
        goto_login = (TextView)findViewById(R.id.Goto_login);

        register = (Button)findViewById(R.id.register_OK);
        clear = (Button)findViewById(R.id.register_clear);

    }

    void set_click(){
        //选择图片
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            }
        });

        //跳转登陆
        goto_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterUserActivity.this, LoginUserActivity.class);
                startActivity(intent);
            }
        });


        //注册
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (account.getText().toString().equals("") || name.getText().toString().equals("")
                        || password.getText().toString().equals("") || confirm_password.getText().toString().equals("")) {
                    Toast.makeText(RegisterUserActivity.this, "不可空白", Toast.LENGTH_SHORT).show();
                } else if (!password.getText().toString().equals(confirm_password.getText().toString())) {
                    Toast.makeText(RegisterUserActivity.this, "密码不一致", Toast.LENGTH_SHORT).show();
                } else {
                    //未选择头像，使用默认头像
                    if (!have_choose) {
                        Resources r = getResources();
                        Uri a = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                                + r.getResourcePackageName(R.drawable.me) + "/"
                                + r.getResourceTypeName(R.drawable.me) + "/"
                                + r.getResourceEntryName(R.drawable.me));
                        my_image = Bitmap_to_base642(get_image_Bitmap(a));
                    }
                    final String register_username = account.getText().toString();
                    final String register_name = name.getText().toString();
                    String register_password = password.getText().toString();


                    //判断网络是否开启
                    ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = cn.getActiveNetworkInfo();
                    if (networkInfo == null || !networkInfo.isConnected()) {
                        Toast.makeText(RegisterUserActivity.this, "网络未连接", Toast.LENGTH_SHORT).show();
                        return;
                    }


                    final Register_packet register_packet =
                            new Register_packet(register_name, register_username, register_password, my_image);




                    /*
                    Bitmap bm = null;
                    byte[] bytes = Base64.decode(my_image, Base64.DEFAULT);
                    bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    imageView.setImageBitmap(bm);
*/
                    //新开线程发送网络请求
                    try {
                        OkHttpClient build = new OkHttpClient.Builder()
                                .connectTimeout(2, TimeUnit.SECONDS)
                                .readTimeout(2, TimeUnit.SECONDS)
                                .writeTimeout(2, TimeUnit.SECONDS)
                                .build();

                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("http://129.204.116.253:8080")

                                .addConverterFactory(GsonConverterFactory.create())

                                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                                // build 即为okhttp声明的变量，下文会讲
                                .client(build)

                                .build();

                        RegisterInterface service = retrofit.create(RegisterInterface.class);

                        service.postRegister(register_packet)
                                .subscribeOn(Schedulers.io())//请求在新的线程中执行
                                .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                                .subscribe(new DisposableObserver<Confirm_packet>() {
                                    @Override
                                    public void onNext(Confirm_packet confirm_packet) {
                                        if(confirm_packet.getStatus()){
                                            User_basic_info user_basic_info = new User_basic_info(register_username, register_name, "该用户暂无个人描述", my_image);
                                            Intent intent = new Intent(RegisterUserActivity.this, MainActivity.class);
                                            intent.putExtra("user", user_basic_info);
                                            intent.putExtra("register", true);
                                            startActivity(intent);
                                        }
                                        else {
                                            Toast.makeText(RegisterUserActivity.this, "注册失败："+confirm_packet.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        Toast.makeText(RegisterUserActivity.this, "访问失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                                        Log.i("test", "onError: "+e.toString());
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });

                    } catch (Exception o) {
                        Toast.makeText(RegisterUserActivity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
                        Log.i("test", "onError: "+o.toString());
                    }

                }

            }
        });



        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                account.setText("");
                name.setText("");
                password.setText("");
                confirm_password.setText("");
            }
        });

    }

    public interface RegisterInterface{
        @POST("/regist")
        Observable<Confirm_packet> postRegister(@Body Register_packet register_packet);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            Uri uri = data.getData();
            imageView.setImageBitmap(get_image_Bitmap(uri));
            my_image = Bitmap_to_base64(get_image_Bitmap(uri));
            have_choose = true;
        }
        else{
            Toast.makeText(RegisterUserActivity.this,"取消图片选择",Toast.LENGTH_SHORT).show();
        }
    }


    private String Bitmap_to_base64(Bitmap bitmap){
        ByteArrayOutputStream a = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, a);
        if(a.toByteArray().length > 20000){
            a.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, a);
        }

        String result = Base64.encodeToString(a.toByteArray(), Base64.DEFAULT);
        return result;
    }

    //将uri转换成bitmap
    private Bitmap get_image_Bitmap(Uri uri){

        try{
            // 读取本地图库uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
            return bitmap;
        }
        catch (Exception e) {
            Toast.makeText(RegisterUserActivity.this,"图片选取失败",Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    private String Bitmap_to_base642(Bitmap bitmap){
        ByteArrayOutputStream a = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, a);

        String result = Base64.encodeToString(a.toByteArray(), Base64.DEFAULT);
        return result;
    }


}
